// 用户状态管理
import { defineStore } from 'pinia'

export interface UserInfo {
  id: string
  mobile: string
  nickname: string
  avatar: string
  token: string
  balance: number
  points: number
  isVip: boolean
}

interface UserState {
  userInfo: UserInfo | null
  isLogin: boolean
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    userInfo: null,
    isLogin: false
  }),
  
  getters: {
    getUserInfo: (state: UserState) => state.userInfo,
    getIsLogin: (state: UserState) => state.isLogin
  },
  
  actions: {
    // 设置用户信息
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo
      this.isLogin = true
      // 保存到本地存储
      uni.setStorageSync('userInfo', userInfo)
    },
    
    // 清除用户信息
    clearUserInfo() {
      this.userInfo = null
      this.isLogin = false
      // 清除本地存储
      uni.removeStorageSync('userInfo')
    },
    
    // 初始化用户信息
    initUserInfo() {
      const userInfo = uni.getStorageSync('userInfo')
      if (userInfo) {
        this.userInfo = userInfo
        this.isLogin = true
      }
    },
    
    // 更新用户余额
    updateBalance(balance: number) {
      if (this.userInfo) {
        this.userInfo.balance = balance
        // 更新本地存储
        uni.setStorageSync('userInfo', this.userInfo)
      }
    },
    
    // 更新用户积分
    updatePoints(points: number) {
      if (this.userInfo) {
        this.userInfo.points = points
        // 更新本地存储
        uni.setStorageSync('userInfo', this.userInfo)
      }
    }
  }
})

// 明确导出类型
export type { UserInfo }